package com.yixun.qfbao.dto.base;

import com.yixun.qfbao.annotation.TYWValid;
import com.yixun.qfbao.dto.exception.OvalUNCheckedException;
import com.yixun.qfbao.exception.XFUNExceptionCode;
import net.sf.oval.ConstraintViolation;
import net.sf.oval.Validator;
import net.sf.oval.configuration.annotation.AnnotationsConfigurer;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Objects;

public class OvalUtil {
	private static Logger logger = LoggerFactory.getLogger(OvalUtil.class);
	
	@SuppressWarnings("unchecked")
	public static <T> T firstRealVal(T... objects) {
		for (Object object : objects) {
			if (object != null && !"".equals(object)) {
				return (T)object;
			}
		}
		return null;
	}
	
	public static String enumValues(Class<?> menum) {
		StringBuilder valstr = new StringBuilder();
		try {
			Object[] values;
			values = (Object[])menum.getMethod("values").invoke(menum);
			valstr.append("[");
			String pre = "";
			for (int i = 0; i < values.length; i++) {
				valstr.append(pre + values[i].getClass().getMethod("getCode").invoke(values[i]));
				pre = ",";
			}
			valstr.append("]");
		} catch (Exception e) {
			logger.error("枚举反射取值: {}", e);
		}
		return valstr.toString();
	}
	
	public static void validate(Object bean) {
		// 初始化
		Validator validator = new Validator(new AnnotationsConfigurer());
		Validator.setMessageResolver(new CustomResourceBundleMessageResolver("zh"));
		// 校验bean值是否合法
		List<ConstraintViolation> violations = validator.validate(bean);
		StringBuilder errormsg = new StringBuilder();
		errormsg.append("参数验证异常 : ");
		if (violations.size() > 0) {
			String errorFiled = "";
			for (ConstraintViolation constraintViolation : violations) {
				String[] fileds =  constraintViolation.getContext().toString().split("\\.");
				errorFiled = fileds[fileds.length-1];
				try {
					TYWValid tywValid = bean.getClass().getDeclaredField(errorFiled).getAnnotation(TYWValid.class);
					if(Objects.nonNull(tywValid) && StringUtils.isNotBlank(tywValid.errorMsg())){
						errormsg = new StringBuilder(tywValid.errorMsg());
					}else{
						errormsg.append(constraintViolation.getMessage().replaceAll(bean.getClass().getName() + ".", ""));
					}
				} catch (NoSuchFieldException e) {
					logger.error("validate error: {}", e);
					errormsg.append(constraintViolation.getMessage().replaceAll(bean.getClass().getName() + ".", ""));
				}
			}
			logger.error("参数: {}, 错误: {}", errorFiled, errormsg);
			throw new OvalUNCheckedException(XFUNExceptionCode.ILLEGAL_PARAMETER.getCode(), errormsg.toString());
		}
	}
	
}
